import requests
import re
from pathlib import Path
from urllib.parse import urlparse

base_dir = '.'
user = 'syske'
pwd = '123456'

def get_token():
    # 创建一个会话对象
    session = requests.Session()
    url = "https://example.cn/platform-api/login"
    # 准备登录凭证
    login_data = {
        'username': user,
        'password': pwd
    }

    # 发送 POST 请求进行登录
    response = session.post(url, data=login_data)
    # print(response.json())
    return response.json()['data']['action_token']
    
cool_token = get_token()

def matchValue(reStr, sourceContent, matchIndex):
    pat = re.compile(reStr) #用()表示1个组，2个组
    m = pat.search(sourceContent)
    if m == None:
        return None
    return m.group(matchIndex) #默认为0，表示匹配整个字符串

# 批量替换html标签
def filter_html(content):
    re_list = [
        r'<font[^>]*>(.*?)</font>'
    ]
    for reStr in re_list:
        content = re.sub(reStr, r'\1', content, flags=re.DOTALL)
    return content

def get_img_url(img_url):
    tmp_img_path = f"{base_dir}/tmp_img"
    # 如果临时文件夹不存在，则创建文件夹
    
    if not Path.exists(Path(tmp_img_path)):
        Path.mkdir(Path(tmp_img_path))
    # 解析 URL 并提取文件名
    parsed_url = urlparse(img_url)
    remote_file_name = Path(parsed_url.path).name
    # 下载远程文件
    response = requests.get(img_url)
    if response.status_code == 200:
        file_path = f'{tmp_img_path}/{remote_file_name}'
        with open(file_path, 'wb') as file:
            file.write(response.content)
        print("远程文件下载成功", file_path)
        return upload_img(file_path)
    else:
        print("远程文件下载失败")
        print("状态码:", response.status_code)
        exit(1)

def upload_img(file_path):
    global cool_token
    # 服务器的上传端点
    upload_url = f'https://example.cn/platform-api/common/upload/image?access_token={cool_token}'
    # 打开本地文件并提交
    with open(file_path, 'rb') as file:
        # files = {'file': (file_path, file)}
        files = {'file': (file_path, file, 'application/octet-stream')}
        response = requests.post(upload_url, files=files)
    
    # 检查响应
    if response.status_code == 200:
        print("文件上传成功")
        print("响应内容:", response.text)
            # 删除本地文件
        Path(file_path).unlink()
        print("本地文件已删除")
        print(response.text)
        return response.text
    else:
        print("文件上传失败")
        print("状态码:", response.status_code)
        print("响应内容:", response.text)

def replace_url(match):
    original_url = match.group(2)
    print(original_url)
    # 下载并替换图片
    new_url = get_img_url(original_url)
    return f'![{match.group(1)}]({new_url})'

def replace_img(line):
    return re.sub(r'!\[(.*?)\]\(([^)]+)\)', replace_url, line)

def markdonw_replace_img(file_path):
    lines = open(file=file_path, encoding="utf-8").read().split('\n')
    updated_lines = []
    for line in lines:
        # 匹配图片并替换
        image_line = replace_img(line)
        updated_line = filter_html(image_line)
        # print(updated_line)
        updated_lines.append(updated_line)
    updated_content = '\n'.join(updated_lines)
    # 提取文件的基本名称（不包括扩展名）
    new_file_name = Path(file_path).stem
    # 将更新后的内容写回文件
    with open(f'{new_file_name}_updated.md', 'w', encoding='utf-8') as file:
        file.write(updated_content)

    print(f"图片 URL 替换完成，已保存到 {new_file_name}_updated.md")

if __name__ == "__main__":
    file_path = "酷学院V8.1.3产品发版大纲.md"
    markdonw_replace_img(file_path)
    # img_url = "https://cdn.nlark.com/yuque/0/2024/png/29143380/1726726810229-16f7c550-68bc-475a-9f9a-810bdd0ca21f.png"
    # new_url = get_img_url(img_url)
    # print(new_url)
    # token = get_token()
    # print(token)